﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DotNetNuke.Entities.Content;
using DotNetNuke.Security.Permissions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Tabs;


namespace iLangl.Customer.DNN
{
	public class SecurityManager
	{
		#region Singelton Pattern


		private static SecurityManager instance;
		private static object mutex = new object();
		/// <summary>
		/// The instance of the SecurityManager.
		/// </summary>
		public static SecurityManager Instance
		{
			get
			{
				if (instance == null)
				{
					lock (mutex)
					{
						if (instance == null)
						{
							instance = new SecurityManager();

						}
					}
				}
				return instance;
			}
		}
		#endregion

		public void LockContent(IList<ModuleInfo> modules)
		{
			PermissionProvider pp = new PermissionProvider();
			foreach(ModuleInfo module in modules)
			{
				foreach (ModulePermissionInfo mpi in module.ModulePermissions)
				{
					if (mpi.PermissionKey == "View")
					{
						continue;
					}
					else
					{
						mpi.AllowAccess = false;
					}
				}
				pp.SaveModulePermissions(module);
			}
		}

		public void LockContent(IList<TabInfo> tabs)
		{
			PermissionProvider pp = new PermissionProvider();
			foreach (TabInfo tab in tabs)
			{
				foreach (TabPermissionInfo mpi in tab.TabPermissions)
				{
					if (mpi.PermissionKey == "View")
					{
						continue;
					}
					else
					{
						mpi.AllowAccess = false;
					}
				}

				pp.SaveTabPermissions(tab);
			}
		}

		public void UnlockContent(IList<CustomerContentEntity> contentstounlock)
		{
			PermissionProvider pp = new PermissionProvider();
			foreach (CustomerContentEntity cce in contentstounlock)
			{
				ContentItem ci = IdentityManager.GetContent(cce.CustomerIdentity);

				if (ci is ModuleInfo)
				{
					ModuleInfo mi = ci as ModuleInfo;
					mi.ModulePermissions.Clear();
					mi.ModulePermissions = PermissionManager.ImportModulePermissions(cce.Permissions);
					pp.SaveModulePermissions(mi);
				}

				if (ci is TabInfo)
				{
					TabInfo tab = ci as TabInfo;
					tab.TabPermissions.Clear();
					TabPermissionCollection tpc  = PermissionManager.ImportTabPermissions(cce.Permissions);
					foreach (TabPermissionInfo tpi in tpc)
					{
						tab.TabPermissions.Add(tpi);
					}
					pp.SaveTabPermissions(tab);
				}
			}
		}
	}
}